package com.hanliy.config;

import com.hanliy.shiro.AdminAuthoriztionRealm;
import com.hanliy.shiro.AdminWebSessionManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author hanyulin
 * @apiNote
 * @date 2021/11/6 13:56
 */
@Configuration
public class ShiroConfig {

    /**
     * 创建realm对象，交给Spring管理
     *
     * @author hanyulin
     * @date 2021/11/6 14:11
     * @return org.apache.shiro.realm.Realm
     */
    @Bean
    public Realm realm() {
        return new AdminAuthoriztionRealm();
    }

    /**
     * 对网站的过滤：路径需要怎么样才能够实现访问，绑定securityManager
     *
     * @param securityManager : 自己定义的defaultWebSecurityManager()
     * @author hanyulin
     * @date 2021/11/6 14:21
     * @return ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager ){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        /*
        FilterChain：
        anon    所有 url 都都可以匿名访问
        authc   需要认证才能进行访问
        user    配置记住我或认证通过可以访问
        perms   拥有对某个资源的权限才能访问
        roles   拥有某个权限才能够访问
        过滤链，从上向下顺序执行，一般将/**放在最为下边
         */
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/admin/add","perms[admin:add]");
        filterMap.put("/admin/update","perms[admin:update]");
        // 拦截admin下面的请求（如果没有认证信息）
        filterMap.put("/admin/**","authc");
        // 所有的请求可以放行
        filterMap.put("/**","anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        // 如果不符合权限规则，设置跳转页面：登录
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        //未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        return shiroFilterFactoryBean;
    }

    @Bean
    public SessionManager sessionManager() {
        return new AdminWebSessionManager();
    }

    /**
     * 绑定reaml
     *
     * @author hanyulin
     * @date 2021/11/6 14:13
     * @return DefaultWebSecurityManager
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 关联自定义的realm
        securityManager.setRealm(realm());
        return securityManager;
    }


}
